<template>
	<div class="home">
		<el-container>
			<!-- 按钮集合 -->
			<el-header class="buttons" style="height: 45px;">
				<el-button type="primary" link @click="Previous">
					返回
				</el-button>
				<div>

					<el-button @click="realTimeView.show = true" type="primary" link>预览</el-button>
					<el-button @click="$refs.file.click()" type="primary" link>导入JSON</el-button>
					<el-button @click="exportJSON" type="primary" link>导出JSON</el-button>
					<el-button @click="catJson" type="primary" link>查看JSON</el-button>
					<el-button @click="reloads" type="danger" size="small"><i
							class="el-icon-delete-solid el-icon--left"></i>重置
					</el-button>
					<el-button @click="Preservation" size="small" type="primary">
						<i class="el-icon-s-promotion"></i>发布
					</el-button>
					<input type="file" ref="file" id="file" accept=".json" @change="importJSON" style="display: none" />

				</div>
			</el-header>

			<!-- 装修操作 -->

			<el-container class="operation">
				<!-- 组件 -->
				<el-aside width="310px" style="display: flex;">
					<el-menu default-active="1" :collapse=true @select="handleSelectMenu">
						<el-menu-item index="1">
							<el-icon><DocumentCopy /></el-icon>
							<span slot="title">页面</span>
						</el-menu-item>
						<el-menu-item index="2">
							<el-icon><Operation /></el-icon>
							<span slot="title">大纲树</span>
						</el-menu-item>
						<el-menu-item index="3">
							<el-icon><SetUp /></el-icon>
							<span slot="title">页面构建</span>
						</el-menu-item>
						<el-menu-item index="4">
							<el-icon><Coin /></el-icon>
							<span slot="title">数据源</span>
						</el-menu-item>
						<el-menu-item index="5">
							<el-icon><MagicStick /></el-icon>
							<span slot="title">源码面板</span>
						</el-menu-item>
					</el-menu>
					<div class="leftslider">
						<sliderassembly v-show="$leftcom=='assembly'" />
						<componenmanagement v-show="$leftcom=='componenmanagement'" />
						<datasourceManagement v-show="$leftcom=='datasource'" />
					</div>

				</el-aside>
				<!-- 手机 -->

				<div class="phone">
					<section class="phoneAll" ref="imageTofile" id="imageTofile">
						<img src="@/assets/images/phoneTop.png" alt="" class="statusBar" />

						<!-- 头部导航 -->
						<headerTop @click.native="headTop" />

						<!-- 主体内容 -->
						<div class="phone-container" 
						:class="pointer.show ? 'pointer-events' : ''"
							:style="{ 'background-color': $pageSchema[0].pageSetup.bgColor,backgroundImage: 'url(' + $pageSchema[0].pageSetup.bgImg + ')',}">
							<dragContainer :parentComponent="$pageSchema[0]"> </dragContainer>
						</div>
						<!-- <div class="phone-container" ></div> -->
						<!-- 手机高度 -->
						<div class="phoneSize">iPhone 8手机高度</div>
						<!-- 底部 -->
						<!-- <phoneBottom /> -->
					</section>
					<!-- 底部 -->
				</div>
				<!-- 页面设置tab -->
				<div class="decorateTab">
					<span :class="$rightcom === 'decorate' ? 'active' : ''" @click="$setRightcom('decorate') ">
						<i class="el-icon-tickets" />
						页面设置
					</span>

				</div>

				<!-- 右侧工具栏 -->
				<div class="decorateAll">
					<!-- 页面设置 -->
					<transition name="decorateAnima">
						<!-- 动态组件 -->
						<rightslider></rightslider>
					</transition>
				</div>

			</el-container>

<!-- 			<realTimeView :datas="realTimeView" :val="{
        id: $pageSchema[0].id,
        name: $pageSchema[0].pageSetup.name,
        templateJson: JSON.stringify($pageSchema[0].pageSetup),
        component: JSON.stringify($pageSchema[0].pageComponents),
      }" /> -->

			<el-dialog title="提示" :visible.sync="jsonDialogVisible" width="30%">
				<!-- <div style="overflow: scroll">{{pageJson}}</div> -->
				<json-viewer :value="pageJson" copyable boxed :expand-depth="5"></json-viewer>

				<span slot="footer" class="dialog-footer">
					<el-button @click="jsonDialogVisible = false">关 闭</el-button>
				</span>
			</el-dialog>

		</el-container>

	</div>
</template>

<script>
	import utils from '@/utils/index' // 方法类=
	import html2canvas from 'html2canvas' // 生成图片
	import FileSaver from 'file-saver' // 导出JSON
	import draggable from 'vuedraggable'
	import JsonViewer from 'vue-json-viewer'
	import 'vue-json-viewer/style.css'

	import {
		mapState,
		mapMutations,
		mapActions
	}
	from 'vuex'
	export default {
		name: 'home',
		components: {
			draggable,
			JsonViewer
		},

		computed: {
			...mapState(['$pageSchema', '$rightcom', '$leftcom', '$currentproperties', '$currentComponent'])
		},
		data() {
			return {
				jsonDialogVisible: false,
				realTimeView: {
					show: false, // 是否显示预览
				},
				id: null, //当前页面
				deleShow: true, //删除标签显示
				index: '', //当前选中的index
				offsetY: 0, //记录上一次距离父元素高度
				pointer: {
					show: false
				}, //穿透
				onlyOne: ['1-5', '1-16'], // 只能存在一个的组件(组件的type)
				pageJson: {},
				menuNav: { // 菜单与组件的映射
					0: '',
					1: 'decorate', // 页面设置
					2: 'componenmanagement', // 大纲树
					3: 'assembly', // 组件面板
					4: 'datasource', //数据源
					5: 'codepanel', //代码面板
				}
			}
		},

		mounted() {
			this.$setCurrentproperties(this.$pageSchema[0].pageSetup)
		},

		methods: {
			...mapMutations(['$setRightcom', '$setCurrentproperties', '$setLeftcom', '$reload']),
			...mapActions(['$reloadAsync']),
			handleSelectMenu(key, keyPath) {

				if (['2', '3','4'].includes(key)) {
					this.$setLeftcom(this.menuNav[key])

				} else if (['1'].includes(key)) {
					this.$setRightcom(this.menuNav[key])
				}


			},
			// 查看JSON
			catJson() {
				this.pageJson = {
					id: this.$pageSchema[0].id,
					name: this.$pageSchema[0].pageSetup.name,
					templateJson: this.$pageSchema[0].pageSetup,
					component: this.$pageSchema[0].pageComponents
				};

				this.jsonDialogVisible = true;


			},
			/**
			 * 保存
			 */
			Preservation() {
				/* 隐藏border和删除图标 */
				this.deleShow = false
				/* 渲染结束截图 */
				this.$nextTick(() => {
					/* 截图 */
					this.toImage()
				})
			},

			/**
			 * 页面截图
			 *
			 * @param {Function} callBack 回调函数
			 */
			toImage() {
				/* 加载 */
				const loading = this.$loading({
					lock: true,
					text: '保存中...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)',
				})

				const imageTofiles = document.querySelector('#imageTofile')
				/* 截图 */
				html2canvas(this.$refs.imageTofile, {
					backgroundColor: null,
					height: imageTofiles.scrollHeight,
					width: imageTofiles.scrollWidth,
					useCORS: true,
				}).then((canvas) => {
					/* 显示border和删除图标 */
					this.deleShow = true
					let url = canvas.toDataURL('image/png')
					const formData = new FormData()
					formData.append('base64File', url)
					loading.close()
				})
			},

			/**
			 * 切换组件位置
			 *
			 * @param {Object} res 组件切换后返回的位置
			 */
			componenmanagement(res) {
				this.$pageSchema[0].pageComponents = res
			},

			/**
			 * 标题切换
			 *
			 * @param {Object} res 当前组件对象
			 */
			headTop() {
				this.$rightcom = 'decorate'

				/* 替换 */
				utils.forEach(this.$pageSchema[0].pageComponents, (res) => {
					/* 修改选中 */
					if (res.active === true) res.active = false
				})
			},


			/* 页面刷新 */
			reloads() {
				this.$confirm('重置后您添加或者修改的数据将会失效, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					})
					.then(() => {
						this.$reloadAsync()
					})
					.catch(() => {})
			},

			// 返回上一步
			Previous() {
				this.$confirm('返回列表您添加或者修改的数据将会失效, 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					})
					.then(() => {
						this.$router.go(-1)
					})
					.catch(() => {})
			},

			// 导出json
			exportJSON() {
				// 将json转换成字符串
				const data = `{

          "id": ${this.$pageSchema[0].id},

          "name": "${this.$pageSchema[0].pageSetup.name}",

          "templateJson": ${JSON.stringify(this.$pageSchema[0].pageSetup)},

          "component": ${JSON.stringify(this.$pageSchema[0].pageComponents)}

        }`
				const blob = new Blob([data], {
					type: ''
				})
				FileSaver.saveAs(blob, `${this.$pageSchema[0].pageSetup.name}.json`)
			},
			// 导入json
			importJSON() {
				const file = document.getElementById('file').files[0]
				const reader = new FileReader()
				reader.readAsText(file)
				let _this = this
				reader.onload = function() {
					// this.result为读取到的json字符串，需转成json对象
					let ImportJSON = JSON.parse(this.result)
					// 检测是否导入成功
					// 导入JSON数据
					_this.id = ImportJSON.id
					_this.pageSetup = JSON.parse(ImportJSON.templateJson)
					_this.pageComponents = JSON.parse(ImportJSON.component)
				}
			},
		},

		watch: {
			/* 监听右侧属性设置切换 */
			$rightcom(newval) {
				if (newval === 'decorate') {
					utils.forEach(this.$pageSchema[0].pageComponents, (res) => {
						/* 修改选中 */
						if (res.active === true) res.active = false
					})
					this.$currentproperties = this.$pageSchema[0].pageSetup
					return
				}
				if (newval === 'componenmanagement') {
					/* 替换 */
					utils.forEach(this.$pageSchema[0].pageComponents, (res) => {
						/* 修改选中 */
						if (res.active === true) res.active = false
					})
					this.$currentproperties = this.$pageSchema[0].pageComponents
				}
			},

		},
	}
</script>

<style lang="scss" scoped>
	.pointer-events {
		pointer-events: none;
	}

	// /deep/ .el-tooltip__popper{
	// 	transition: all 0.8s !important;
	// 	background-color: #155bd4 !important;
	// }



	::v-deep .el-message-box__wrapper .el-message-box__message p {
		overflow: scroll;
	}

	.home {
		width: 100%;
		height: 100vh;

		::v-deep .el-message-box__message p {
			overflow: scroll;
		}

		/* 按钮集合 */

		.buttons {
			height: 45px;
			border-bottom: 1px solid #ebedf0;
			display: flex;
			justify-content: space-between;
			box-sizing: border-box;
			padding-right: 15px;
			align-items: center;

			/* 下拉 */
			::v-deep .el-button {
				font-weight: normal;
			}


		}

		.leftslider {
			width: 100%;
			height: 100%;
			overflow-y: auto;
			border-right: 1px solid #ebedf0;
			box-sizing: border-box;
			padding: 0 5px;
			background: #fff;
		}

		/* 操作主体 */

		.operation {
			width: 100%;
			height: calc(100vh - 45px);
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			padding-bottom: 5px;

			::v-deep .el-menu--collapse {
				// width: 50px;
			}

			::v-deep .el-menu {
				.el-menu-item {
					.el-tooltip {
						padding: 0px 12px !important;
					}
				}
			}
		}

		/* 手机 */

		.phone {
			width: 100%;
			height: calc(100vh - 45px);

			display: flex;
			justify-content: center;
			background: #f7f8fa;

			&::-webkit-scrollbar {
				width: 1px;
			}

			// &::-webkit-scrollbar-thumb {
			//   background-color: #155bd4;
			// }

			/* 手机样式 */

			.phoneAll {
				width: 375px;
				height: 770px;
				box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.4);
				margin: 25px 0;
				position: relative;

				/* 手机高度 */

				.phoneSize {
					position: absolute;
					left: -137px;
					top: 660px;
					font-size: 12px;
					color: #a2a2a2;
					border-bottom: 1px solid #dedede;
					width: 130px;
					height: 21px;
					line-height: 21px;
				}

				/* 状态栏 */

				.statusBar {
					width: 100%;
					display: block;
				}

				/* 主体内容 */

				.phone-container {
					height: 100%;
					box-sizing: border-box;
					cursor: pointer;
					width: 100%;
					position: relative;
					background-repeat: no-repeat;
					background-size: 100% 100%;
					overflow-y: auto;
					overflow-x: visible;
					margin-bottom: 20px;

					.componentsClass {
						border: 1px dashed #155bd4;

						&:hover {
							border: 1px dashed #155bd4;
						}
					}
				}
			}
		}

		/* 右侧工具栏 */

		.decorateAll {
			width: 350px;
			min-width: 350px;
			height: calc(100vh - 45px);
			overflow-y: scroll;
			overflow-x: hidden;
			position: relative;
			padding: 0 12px;
			background: #fff;

			&::-webkit-scrollbar {
				width: 1px;
			}

			&::-webkit-scrollbar-thumb {
				background-color: #155bd4;
			}
		}

		/* 页面设置tab */

		.decorateTab {
			position: fixed;
			display: flex;
			right: 380px;
			top: 115px;
			flex-direction: column;
			// font-size: 14px;

			span {
				background-color: #fff;
				box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
				border-radius: 2px;
				width: 94px;
				height: 32px;
				display: inline-block;
				text-align: center;
				line-height: 32px;
				margin-bottom: 12px;
				transition: all 0.8s;
				cursor: pointer;

				&.active {
					background-color: $uni-color-primary;
					color: #fff;
				}

				/* 图标 */

				i {
					// font-size: 12px;
					margin-right: 5px;
				}
			}
		}
	}

	/* 动画 */
	.decorateAnima-enter-active {
		transition: all 0.3s ease;
	}

	.decorateAnima-leave-active {
		transition: all 0.3s ease;
	}

	.decorateAnima-enter {
		transform: translate(5px, 5px);
		opacity: 0;
	}

	.decorateAnima-leave-to {
		transform: translate(5px, 5px);
		opacity: 0;
	}
</style>